﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

namespace Jarvis.Sensors
{
    class ProcessSensor : Sensor
    {
        private string active_process = "Unknown";
        private DateTime last_switch = new DateTime();

        [DllImport("user32.dll")]
        static extern int GetForegroundWindow();

        public ProcessSensor() 
            : base(1000)
        {
            this.name = "Running Processes";
        }

        public static Boolean IsRunning(String processName)
        {
            List<object> processList = new List<object>(); 
            
            Process[] processes = System.Diagnostics.Process.GetProcesses(Environment.MachineName);

            int active = GetForegroundWindow();

            foreach (Process p in processes)
            {
                if (p.ProcessName.Equals(processName))
                    return true;
            }

            return false;
        }

        public override void Sense(Object stateInfo)
        {
            DateTime now = DateTime.Now;

            List<object> processList = new List<object>(); 
            
            Process[] processes = System.Diagnostics.Process.GetProcesses(Environment.MachineName);

            int active = GetForegroundWindow();

            foreach (Process p in processes)
            {
                try
                {
                    IntPtr handle = p.MainWindowHandle;
                    long process_handle = handle.ToInt64();

                    if (process_handle != 0)
                    {
                        processList.Add(p.ProcessName);

                        if (process_handle == active && 
                            !(p.ProcessName.Equals("Jarvis") || p.ProcessName.Equals("Jarvis.vshost"))) // make better
                        {
                            if (!active_process.Equals(p.ProcessName))
                                last_switch = now;

                            active_process = p.ProcessName;
                        }
                    }
                }
                catch (Exception)
                {

                }
            }

            Sensor cn = new Sensor("Active Process");
            cn.log(active_process);

            Int64 ticks = now.Ticks - last_switch.Ticks;

            cn = new Sensor("Active Process Time");
            cn.log((Double)(ticks / 10000000));

            this.log(processList);
        }
    }
}
